package net.tsz.afinal.download;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import com.example.aymutilused2.R;
import net.tsz.afinal.sdcard.SdcardHelper;
import net.tsz.afinal.toast.ToastUtil;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.*;

/**
 * Created by Administrator on 2015/7/4 0004.
 */
public class DownloadService extends Service {
	private final String TAG = super.getClass().getName();
	private final String fileLoadingHZ = ".aymdl";
	private Binder serviceBinder = new DownloadServiceBinder();
	private NotificationManager manager;
	private Timer timer = new Timer();
	private Map<DownLoadQueue, Notification> MyDownLoadQueues = new HashMap();
	private List<DownLoadQueue> downLoadedQueues = new Vector();
	private SdcardHelper sdHelper;
	private boolean isNoSdcard = false;
	private final int what_SDFreeSizeInadequate = -1;
	/**
	 * 下载完成action
	 */
	public static final String ACTION_DOWNLOAD_FINISHED="mydownload_finished";
	/**
	 * 开始下载的action
	 */
	public static final String ACTION_DOWNLOAD_START="mydownload_start";

	/**
	 * 下载异常
	 */
	public static final String ACTION_DOWNLOAD_ERROR="mydownload_error";

	/**
	 * 下载的id
	 */
	public static final String  ACTION_DOWNLOAD_ID="downlaod_id";
	/**
	 * 通知栏点击事件
	 */
	public static final String ACTION_DOWNLOAD_NOTIFICATION_CLICKED="mydownload_notify_click";
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch(msg.what) {
				case -1:
					ToastUtil.initToast(DownloadService.this).showToast(R.string.text_downLoad_SDcardMemory_downloadedError);
				default:
			}
		}
	};

	public DownloadService() {
	}

	public IBinder onBind(Intent intent) {
		return this.serviceBinder;
	}

	public void onCreate() {
		super.onCreate();
		this.manager = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
		this.sdHelper = new SdcardHelper();
		this.isNoSdcard = !SdcardHelper.ExistSDCard();
	}


	public void onDestroy() {
		this.timer.cancel();
		super.onDestroy();
	}

	private void startDownLoad(final DownLoadQueue queue) {
		(new Thread() {
			public void run() {
				try {
					DefaultHttpClient e = new DefaultHttpClient();
					HttpGet get = new HttpGet(queue.getDownLoadUrl());
					HttpResponse response = e.execute(get);
					HttpEntity entity = response.getEntity();
					long length = entity.getContentLength();
					queue.setOffSize(length);
					if(SdcardHelper.getSDFreeSize() <= length / 1024L) {
						queue.setCancel(true);
						DownloadService.this.handler.sendEmptyMessage(-1);
						return;
					}

					InputStream is = entity.getContent();
					FileOutputStream fileOutputStream = null;
					File file = null;
					String endName = null;
					if(is != null) {
						file = DownloadService.this.creatFile(queue.getDownLoadedPath());
						endName = file.getAbsolutePath().substring(0, file.getAbsolutePath().length() - ".aymdl".length());
						queue.setFileName(endName);
						fileOutputStream = new FileOutputStream(file);
						byte[] b = new byte[1024];
						boolean charb = true;
						int count = 0;

						int charb1;
						while((charb1 = is.read(b)) != -1 && !queue.isCancel()) {
							fileOutputStream.write(b, 0, charb1);
							count += charb1;
							queue.setDownSize((long)count);
						}
					}

					fileOutputStream.flush();
					if(fileOutputStream != null) {
						fileOutputStream.close();
					}

					if(!queue.isCancel()) {
						queue.setDownSize(length);
						file.renameTo(new File(endName));
					}
				} catch (Exception var14) {
					DownloadService.this.MyDownLoadQueues.remove(queue);
					DownloadService.this.manager.cancel(queue.getId());
					sendDownLoadErrorBroadcast(queue);
				}

			}
		}).start();
	}



	public DownLoadQueue addQueue(DownLoadQueue queue) {
		if(this.isNoSdcard) {
			ToastUtil.initToast(this).showToast(R.string.text_downLoad_nosdcard);
			return queue;
		} else {
			Set set = this.MyDownLoadQueues.keySet();
			Iterator iterator = set.iterator();

			while(iterator.hasNext()) {
				DownLoadQueue MyDownLoadQueue = (DownLoadQueue)iterator.next();
				if(queue.getId() == MyDownLoadQueue.getId()) {
					return MyDownLoadQueue; //已经包含 不需要下载
				}
			}

			synchronized(this.MyDownLoadQueues) {
				this.MyDownLoadQueues.put(queue,null );
				if(this.MyDownLoadQueues.size() == 1) {
					this.timer.schedule(new MyTimerTask(), 500L, 500L);
				}
			}

			this.startDownLoad(queue);
			return queue;
		}
	}

	public List<DownLoadQueue> getQueueList() {
		ArrayList dlqs = new ArrayList();
		dlqs.addAll(this.MyDownLoadQueues.keySet());
		return dlqs;
	}

	public void stopQueue(int queueId) {
		Set set = this.MyDownLoadQueues.keySet();
		Iterator iterator = set.iterator();

		while(iterator.hasNext()) {
			DownLoadQueue myDownLoadQueue = (DownLoadQueue)iterator.next();
			if(queueId == myDownLoadQueue.getId()) {
				Map var5 = this.MyDownLoadQueues;
				synchronized(this.MyDownLoadQueues) {
					myDownLoadQueue.setCancel(true);
					return;
				}
			}
		}

	}

	private File creatFile(String filePath) throws Exception {
		File file = new File(filePath);
		if(!file.getParentFile().exists()||!file.getParentFile().isDirectory()){
			file.getParentFile().mkdirs();
		}
		boolean isNO = true;
		int i = 1;

		while(isNO) {
			if(file.exists()) {
				int index = filePath.lastIndexOf(".");
				if(index == -1) {
					if(i == 1) {
						filePath = filePath + i;
					} else {
						filePath = filePath.substring(0, filePath.length() - 1);
					}
				} else if(i == 1) {
					filePath = (new StringBuffer(filePath)).insert(index, "(" + i + ")").toString();
				} else {
					filePath = (new StringBuffer(filePath)).replace(filePath.indexOf("("), filePath.indexOf(")") + 1, "(" + i + ")").toString();
				}

				file = new File(filePath);
				++i;
			} else {
				isNO = false;
			}
		}

		filePath = filePath + ".aymdl";
		file = new File(filePath);
		if(file.exists()) {
			file.delete();
		}

		return file;
	}

	public class DownloadServiceBinder extends Binder {
		public DownloadServiceBinder() {
		}

		public DownloadService getService() {
			return DownloadService.this;
		}
	}

	private class MyTimerTask extends TimerTask {
		private MyTimerTask() {
		}

		public void run() {
			this.updataDownLoadInfo();
		}

		private void updataDownLoadInfo() {
			Set downLoadSet = DownloadService.this.MyDownLoadQueues.keySet();
			Intent intent = null;
			Iterator iterator = downLoadSet.iterator();
			try {
				while(iterator.hasNext()) {
					DownLoadQueue myDownLoadQueue = (DownLoadQueue)iterator.next();
					if(myDownLoadQueue.isCancel()) {
						DownloadService.this.MyDownLoadQueues.remove(myDownLoadQueue);
						DownloadService.this.manager.cancel(myDownLoadQueue.getId());
					} else {
						Notification notification = DownloadService.this.MyDownLoadQueues.get(myDownLoadQueue);
						try {
							intent = new Intent(Intent.ACTION_VIEW);
						} catch (Exception var7) {
						}
						if(notification == null) {
							notification = new Notification();
							notification.icon = myDownLoadQueue.getIconResId();
							this.updataNotify(intent, myDownLoadQueue, notification);
							DownloadService.this.MyDownLoadQueues.put(myDownLoadQueue, notification);
							sendStartDownloadBroadcast(myDownLoadQueue);
						} else {
							this.updataNotify(intent, myDownLoadQueue, notification);
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

		private void updataNotify(Intent intent, DownLoadQueue myDownLoadQueue, Notification notification) {
			PendingIntent intent2 = null;
			if(intent != null && (!myDownLoadQueue.isDownLoadOK() || myDownLoadQueue.isDownLoadOK() && myDownLoadQueue.getOpenFileType() != null)) {
				intent.putExtra("isToStop", true);
				intent.putExtra("queue", myDownLoadQueue);

				if(myDownLoadQueue.isDownLoadOK() && myDownLoadQueue.getOpenFileType() != null && myDownLoadQueue.isDownLoadedAutoopenFile()) {
					myDownLoadQueue.OpenFile(DownloadService.this.getApplicationContext());
				}
			}
			if(myDownLoadQueue.isDownLoadOK()){
				notification.flags=Notification.FLAG_AUTO_CANCEL;
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.setDataAndType(Uri.parse(myDownLoadQueue.getDownLoadedPath()), "application/vnd.android.package-archive");
				sendFinishDownloadBroadcast(myDownLoadQueue);
			}
			try {
				intent2 = PendingIntent.getActivity(DownloadService.this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
			} catch (Exception var6) {
			}
			notification.setLatestEventInfo(DownloadService.this, myDownLoadQueue.getName(), this.getProcess(myDownLoadQueue), intent2);
			DownloadService.this.manager.notify(myDownLoadQueue.getId(), notification);

		}

		private String getProcess(DownLoadQueue queue) {
			String string = ProgressGet100Util.get100_00Progress(queue.getDownSize(), queue.getOffSize());
			if("100.00%".equals(string)) {
				synchronized(DownloadService.this.MyDownLoadQueues) {
					DownloadService.this.downLoadedQueues.add(queue);
					DownloadService.this.MyDownLoadQueues.remove(queue);
				}

				return DownloadService.this.getString(R.string.text_downLoadedfinish);
			} else {
				return DownloadService.this.getString(R.string.text_downLoaded) + string;
			}
		}
	}

	/**
	 * 下载完成的广播
	 * @param myDownLoadQueue
	 */
	private void sendFinishDownloadBroadcast(DownLoadQueue myDownLoadQueue) {
		if(myDownLoadQueue.isDownLoadOK()){ //下载完成
			Intent downloadFinishedIntent=new Intent(ACTION_DOWNLOAD_FINISHED);
			downloadFinishedIntent.putExtra(ACTION_DOWNLOAD_ID,myDownLoadQueue.getId());
			sendBroadcast(downloadFinishedIntent);
		}
	}

	/**
	 * 开始下载
	 * @param myDownLoadQueue
	 */
	private void sendStartDownloadBroadcast(DownLoadQueue myDownLoadQueue) {
		Intent downloadFinishedIntent=new Intent(ACTION_DOWNLOAD_START);
		downloadFinishedIntent.putExtra(ACTION_DOWNLOAD_ID,myDownLoadQueue.getId());
		sendBroadcast(downloadFinishedIntent);
	}

	/**
	 *	下载异常的广播
	 */
	private void sendDownLoadErrorBroadcast(DownLoadQueue myDownLoadQueue) {
		Intent downloadFinishedIntent=new Intent(ACTION_DOWNLOAD_ERROR);
		downloadFinishedIntent.putExtra(ACTION_DOWNLOAD_ID,myDownLoadQueue.getId());
		sendBroadcast(downloadFinishedIntent);
	}
}
